<template>
  <div class="app-container">
    <question-bank ref="questionBank" @setQuestionInfo="setQuestionInfo"/>
    <common-select ref="comSel" @setSelectInfo="setSelectInfo"/>
    <Import ref="import" :data="bankId" @setQuestionInfo="setQuestionInfo"/>
    <question ref="que"/>
    <div class="el-dialog-div">
      <el-form ref="form" :model="form.check" :rules="rules"  label-width="150px">
        <div class="dd-portlet">
          <div class="dd-title">
            <span>考试信息</span>
          </div>
          <div class="dd-body">
            <el-row>
              <el-col :span="8">
                <el-form-item label="考核名称" prop="checkName">
                  <el-input v-model="form.check.checkName" maxlength="20" style="width: 320px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="考核类型" class="dd-label" prop="checkType">
                  <el-select v-model="form.check.checkType" style="width: 320px" placeholder="考核类型">
                    <el-option v-for="item in dictMap.check_type" :key="item.value" :label="item.label"
                               :value="item.value-0">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合格分值">
                  <el-input-number v-model.number="form.check.standardScore" step-strictly :min="1" :max="100" :step="1"
                                   controls-position="right" style="width: 320px;"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="答题时限(分钟)">
                  <el-input-number v-model.number="form.check.limeTime" :min="1" :max="150" step-strictly controls-position="right" style="width: 320px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker
                    v-model="form.check.startTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择日期" style="width: 320px;">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker
                    v-model="form.check.endTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择日期" style="width: 320px;">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="题目是否随机" class="dd-label" prop="status">
                  <el-select v-model="form.check.isRandom" style="width: 320px" placeholder="是否随机">
                    <el-option v-for="item in dictMap.is_random" :key="item.value" :label="item.label"
                               :value="item.value-0">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <div v-if="form.check.isRandom===1">
                <el-col :span="8">
                  <el-form-item label="多选题目数量">
                    <el-input-number v-model.number="form.check.multipleNum" :min="1" :max="100" step-strictly
                                     controls-position="right" style="width: 320px;"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="单选题目数量">
                    <el-input-number v-model.number="form.check.singleNum" :min="1" :max="100" step-strictly controls-position="right" style="width: 320px;"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="判断题目数量">
                    <el-input-number v-model.number="form.check.judgeNum" :min="1" :max="100"  step-strictly controls-position="right" style="width: 320px;"/>
                  </el-form-item>
                </el-col>
              </div>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="考核描述">
                  <el-input
                    type="textarea"
                    :autosize="{ minRows: 7, maxRows: 10}"
                    placeholder="请输入考核描述"
                    v-model="form.check.checkDesc" style="width: 320px;">
                  </el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="8">
                <el-form-item label="封面图">
                  <el-upload
                    class="avatar-uploader"
                    :action="fileUploadUrl"
                    :show-file-list="false"
                    :on-success="handleSuccess"
                    :before-upload="beforeUpload">
                    <img v-if="coverImg" :src="coverImg" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-col> -->
            </el-row>
          </div>
        </div>
        <div class="dd-title">
          <span>考核题库</span>
        </div>
        <div class="dd-body">
          <el-form-item label="题库" v-if="form.check.isRandom===0">
            <el-link type="success" @click="toImport()">导入题目</el-link>
          </el-form-item>
          <el-form-item label="题库" v-if="form.check.isRandom===1">
            <el-link type="danger" @click="selectQuestion">选择题库</el-link>
          </el-form-item>
          <el-form-item label="题库列表">
            <div class="personDiv" style="height: 100px">
              <el-tag v-for="bank in form.banks"
                      :key="bank.bankId"
                      style="cursor: pointer"
                      @click="handleClick(bank)"
                      closable type="info"
                      @close="handleClose(bank)">
                {{bank.bankName}}
              </el-tag>
            </div>
          </el-form-item>
        </div>
        <div class="dd-title">
          <span>考核人员</span>
        </div>
        <div class="dd-body">
          <el-form-item label="人员选择">
            <el-link type="primary" @click="selectUser" :underline="false">人员选择</el-link>
          </el-form-item>
          <el-form-item label="人员列表">
            <div class="personDiv">
              <el-tag v-for="user in form.checkUser" :key="user.userId" closable type="info"
                      @close="deletePersonnel(user)">{{user.userName}}
              </el-tag>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="footer">
      <el-button type="info" @click="goBack" round>取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit" round>确认</el-button>
    </div>
  </div>
</template>

<script>
  import { add, info } from '@/api/business/check'
  import questionBank from '../components/questionBank'
  import commonSelect from '../components/commonSelect'
  import { getPostPageList } from '@/api/business/user'
  import initDict from '@/mixins/initDict'
  import Import from '../questionBank/Import'
  import question from './question'

  export default {
    mixins: [initDict],
    components: { questionBank, commonSelect, question, Import },

    data() {
      return {
        loading: false,
        fileUploadUrl: process.env.FILE_UPLOAD,
        queryId: this.$route.query.id,
        coverImg: null,
        bankId: {},
        objCoverImg: [],
        form: {
          check: {
            id: null,
            checkName: '',
            checkDesc: '',
            coverImg: '',
            startTime: '',
            endTime: '',
            limeTime: 10,
            checkType: null,
            isRandom: 1,
            multipleNum: 5,
            singleNum: 15,
            judgeNum:5,
            standardScore: 60
          },
          banks: [],
          checkUser: []
        },
        rules: {
          checkName: [
            { required: true, message: '请输入考核名称', trigger: 'blur' }
          ],
          checkType: [
            { required: true, message: '请选择考核类型', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '请选择开始时间', trigger: 'blur' }
          ],
          endTime: [
            { required: true, message: '请选结束时间', trigger: 'blur' }
          ],
        }
      }
    },
    created() {
      this.$nextTick(() => {
        this.getDictMap('check_type,is_random')
        if (this.queryId) {
          this.getCheckInfo(this.queryId)
        }
      })
    },
    methods: {
      doSubmit() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.doAdd()
          }
        })
      },
      doAdd() {
        if (this.form.checkUser.length === 0) {
          this.$message.error('请选择考核人员')
          return
        }
        if (this.form.banks.length === 0) {
          this.$message.error('请设置考核题库')
          return
        }
        add(this.form).then(res => {
          this.$notify({
            title: '操作成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.goBack()
        }).catch(err => {
          this.loading = false
          console.log(err)
        })
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
      },
      handleSuccess(response, file, fileList) {
        this.objCoverImg = []
        const uploadFile = {
          name: file.name,
          url: file.response
        }
        this.coverImg = uploadFile.url
        this.objCoverImg.push(uploadFile)
        this.form.check.coverImg = JSON.stringify(this.objCoverImg)
      },
      toImport() {
        this.bankId = { bankId: '0' }
        this.$refs.import.visible = true
      },
      setQuestionInfo(data) {
        this.form.banks = data
        data.forEach(item => this.form.banks.push(item))
        this.form.banks = Array.from(new Set(this.form.banks))
      },
      selectQuestion() {
        this.$refs.questionBank.dialog = true
        this.$refs.questionBank.init()
      },
      selectUser() {
        this.$refs.comSel.dialog = true
      },
      deletePersonnel(user) {
        this.form.checkUser.splice(this.form.checkUser.indexOf(user), 1)
      },
      setSelectInfo(data) {
        if (data != null) {
          if (data.type === 4) {
            this.setUserInfo(data.data)
          } else {
            const params = this.getQueryParams(data)
            getPostPageList(params).then(data => {
              this.setUserInfo(data.content)
            })
          }
        }
      },
      getQueryParams(data) {
        const params = { size: 10000, roleCode: 'r_student' }
        const paramsIds = data.data.map(item => item.id)
        switch (data.type) {
          case 1:
            params.deptIds = paramsIds
            break
          case 2:
            params.jobs = paramsIds
            break
          case 3:
            params.specialtyIds = paramsIds
            break
        }
        return params
      },
      setUserInfo(data) {
        this.form.checkUser = []
        data.forEach(item => {
          const user = {
            userId: item.id,
            userName: item.name
          }
          this.form.checkUser.push(user)
        })
        this.form.checkUser = Array.from(new Set(this.form.checkUser))
      },
      handleClose(bank) {
        this.form.banks.splice(this.form.banks.indexOf(bank), 1)
      },
      handleClick(bank) {
        this.$refs.que.id = bank.bankId
        this.$refs.que.dialog = true
      },
      getCheckInfo(checkId) {
        info(checkId).then(result => {
          this.form = result
          if (result.check.coverImg) {
            let rowObj = JSON.parse(result.check.coverImg)
            this.coverImg = rowObj[0].url
          }
        })
      },
      goBack() {
        this.$router.go(-1)
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .app-container{
    border: none;
    background-color: #ffffff;
    padding: 5px;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .footer {
    height: 100px;
    width: 100%;
    text-align: center;
    bottom: 0;
  }

  .personDiv {
    width: 100%;
    height: 200px;
    overflow: auto;
    border: 1px dashed #dcdfe6;
  }

  .el-tag.el-tag--info{
      margin-left: 5px
  }
  .el-tag + .el-tag {
    margin: 5px 10px;
  }

</style>
